<template>
  <div class="rating-component">
    <div
      class="scroll-container"
      ref="scrollContainer"
      @mousedown="startDrag"
      @touchstart="startDrag"
      @mousemove="drag"
      @touchmove="drag"
      @mouseup="endDrag"
      @mouseleave="endDrag"
      @touchend="endDrag"
    >
      <!-- 使用 v-for 循环渲染 rating-info 盒子 -->
      <div
        v-for="(item, index) in ratingInfos"
        :key="index"
        class="rating-info snap-item"
      >
        <div
          style="
            display: flex;
            flex-direction: column;
            justify-content: space-between;
          "
        >
          <div class="rating-star">
            <div class="rating-star-image">
              <img
                :src="getPlatformLogo(item.platform)"
                :alt="item.platform + ' logo'"
                @error="handleImageError"
                style="width: 100%; height: 100%; object-fit: contain"
              />
            </div>
            <div class="rating-star-text">
              <div class="rating-star-title">{{ item.platform }}</div>
              <div class="rating-star-details">
                <span class="rating-value">{{ item.score }}</span>
                <i class="el-icon-star-on" style="color: #efb82c"></i>
                <span class="rating-review-count"
                  >({{ formatNumber(item.reviews) }} Reviews)</span
                >
              </div>
            </div>
          </div>
          <div class="rating-empty-space"></div>
          <div class="rating-response-rate">
            <div
              style="
                width: 100%;
                flex-direction: column;
                justify-content: space-between;
              "
            >
              <div class="response-rate-info">
                <div class="response-rate-label">Response rate</div>
                <div class="response-rate-value">{{ item.responseRate }}%</div>
                <!-- <div>
                  <img src="@/assets/updown.png" alt="" />
                </div> -->
              </div>
              <div class="response-time-info">
                avg response time {{ item.avgResponseTime }}
              </div>
              <div class="el-progress-container">
                <el-progress
                  :text-inside="false"
                  :stroke-width="10"
                  :percentage="70"
                ></el-progress>
              </div>
              <div class="number">
                <div class="guests-num">
                  Guests: <span>{{ item.guests }}</span>
                </div>
                <div class="reviews-num">
                  Reviews: <span>{{ item.review }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 指示圆点 -->
    <div class="carousel-indicators">
      <span
        v-for="(_, index) in 3"
        :key="index"
        :class="{ active: currentIndex === index }"
        @click="goToSlide(index)"
      ></span>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex"; // 关键：导入 mapActions
// API
import { Reviews, Dashboard } from "@/api/information.js";
export default {
  data() {
    return {
      ratingInfos: [{}, {}, {}, {}], // 轮播数据
      currentIndex: 0, // 当前显示的索引
      intervalId: null, // 自动轮播定时器
      transitionDuration: 500, // 过渡动画时间（毫秒）
      autoplaySpeed: 3000, // 自动轮播速度（毫秒）

      // 拖拽相关状态
      isDragging: false,
      startX: 0,
      scrollLeft: 0,
      isTransitioning: false,
    };
  },
  computed: {
    currentHotelId() {
      return this.$store.state.hotel.currentHotelId;
    },
  },
  methods: {
    formatNumber(num) {
      if (typeof num !== "number" || isNaN(num)) {
        return num;
      }

      // 示例：格式化为英语（美国）风格，保留0位小数
      return new Intl.NumberFormat("en-US", {
        minimumFractionDigits: 0,
        maximumFractionDigits: 0,
      }).format(num);
    },
    format(percentage) {
      return percentage === 100 ? "满" : `${percentage}%`;
    },
    // 切换到指定幻灯片
    goToSlide(index) {
      if (this.isTransitioning || index === this.currentIndex) return;

      this.isTransitioning = true;
      this.currentIndex = index;

      // 直接使用scrollLeft平滑滚动
      const container = this.$refs.scrollContainer;
      const targetPosition = index * this.getItemWidth();

      // 添加平滑滚动效果
      container.style.scrollBehavior = "smooth";
      container.scrollLeft = targetPosition;

      // 滚动完成后重置状态
      setTimeout(() => {
        this.isTransitioning = false;
        container.style.scrollBehavior = "auto"; // 重置为默认行为
      }, this.transitionDuration);
    },

    // 获取项目宽度（包括间距）
    getItemWidth() {
      if (!this.$refs.scrollContainer || this.ratingInfos.length === 0)
        return 0;
      const item = this.$refs.scrollContainer.querySelector(".rating-info");
      if (!item) return 0;

      const style = window.getComputedStyle(item);
      const marginRight = parseFloat(style.marginRight) || 0;
      return item.offsetWidth + marginRight;
    },

    // 计算当前应该显示的索引
    calculateCurrentIndex() {
      if (!this.$refs.scrollContainer) return;

      const container = this.$refs.scrollContainer;
      const itemWidth = this.getItemWidth();
      const scrollPosition = container.scrollLeft;

      // 计算当前可见的卡片索引
      const index = Math.round(scrollPosition / itemWidth);

      // 避免索引越界
      if (index >= 0 && index < this.ratingInfos.length) {
        this.currentIndex = index;
      }
    },

    getPlatformLogo(platform) {
      const logoMap = {
        Booking: require("@/assets/platforms/booking.png"),
        Expedia: require("@/assets/platforms/expedia.png"),
        Tripadvisor: require("@/assets/platforms/tripadvisor.png"),
        Google: require("@/assets/platforms/google.png"),
        Trip: require("@/assets/platforms/trip.png"),
      };
      return logoMap[platform] || require("@/assets/platforms/booking.png");
    },

    handleImageError(event) {
      event.target.src = require("@/assets/platforms/default.png");
      event.target.style.objectFit = "contain"; // 确保默认图片正常显示
    },

    async getDashboard() {
      try {
        const res = await Dashboard({
          hotelId: this.currentHotelId,
        });
        console.log("返回的数据", res.data);
        // // 转换数据结构
        this.ratingInfos = [
          {
            platform: "Booking",
            score: res.data.reviewSummary.bookingScore,
            reviews: res.data.reviewSummary.bookingReviews,
            responseRate: 70,
            avgResponseTime: "5 days",
            guests: 487, // 300-800
            unreplied: Math.floor(
              res.data.reviewSummary.bookingReviews * 0.067
            ), // 6.7%
            flagged: Math.floor(res.data.reviewSummary.bookingReviews * 0.023), // 2.3%
            review: 112, // 50-150
          },
          {
            platform: "Expedia",
            score: res.data.reviewSummary.expediaScore,
            reviews: res.data.reviewSummary.expediaReviews,
            responseRate: 75,
            avgResponseTime: "3 days",
            guests: 623, // 300-800
            unreplied: Math.floor(
              res.data.reviewSummary.expediaReviews * 0.058
            ), // 5.8%
            flagged: Math.floor(res.data.reviewSummary.expediaReviews * 0.027), // 2.7%
            review: 87, // 50-150
          },
          {
            platform: "Tripadvisor",
            score: res.data.reviewSummary.tripadvisorScore,
            reviews: res.data.reviewSummary.tripadvisorReviews,
            responseRate: 80,
            avgResponseTime: "8 days",
            guests: 372, // 300-800
            unreplied: Math.floor(
              res.data.reviewSummary.tripadvisorReviews * 0.075
            ), // 7.5%
            flagged: Math.floor(
              res.data.reviewSummary.tripadvisorReviews * 0.024
            ), // 2.4%
            review: 143, // 50-150
          },
          {
            platform: "Google",
            score: res.data.reviewSummary.googleScore,
            reviews: res.data.reviewSummary.googleReviews,
            responseRate: 85,
            avgResponseTime: "1 day",
            guests: 715, // 300-800
            unreplied: Math.floor(res.data.reviewSummary.googleReviews * 0.053), // 5.3%
            flagged: Math.floor(res.data.reviewSummary.googleReviews * 0.028), // 2.8%
            review: 67, // 50-150
          },
          {
            platform: "Trip",
            score: res.data.reviewSummary.tripScore,
            reviews: res.data.reviewSummary.tripReviews,
            responseRate: 85,
            avgResponseTime: "2 day",
            guests: 538, // 300-800
            unreplied: Math.floor(res.data.reviewSummary.tripReviews * 0.062), // 6.2%
            flagged: Math.floor(res.data.reviewSummary.tripReviews * 0.026), // 2.6%
            review: 124, // 50-150
          },
        ];

        console.log("处理后ratingInfos:", this.ratingInfos);

        // 提交到store前确保数据不为空
        if (this.ratingInfos.length > 0) {
          this.$store.commit("dashBoard/SET_RATING_INFOS", this.ratingInfos);
          console.log("已提交数据到store");
        } else {
          console.log("数据为空，未提交到store");
        }

        this.hotelInfo = res.data.basicInfo;

        // 数据加载完成后重新计算索引
        this.$nextTick(() => {
          this.calculateCurrentIndex();
        });
      } catch (error) {
        console.error("请求失败:", error);
      }
    },

    // // 重置自动轮播定时器
    // resetAutoplay() {
    //   clearInterval(this.intervalId);
    //   this.intervalId = setInterval(() => {
    //     this.currentIndex = (this.currentIndex + 1) % this.ratingInfos.length;
    //     this.goToSlide(this.currentIndex);
    //   }, this.autoplaySpeed);
    // },

    // 监听滚动事件，更新当前索引
    handleScroll() {
      if (this.isDragging || this.isTransitioning) return;
      this.calculateCurrentIndex();
    },

    // 开始拖拽
    startDrag(e) {
      if (this.isTransitioning) return;

      // 清除自动轮播
      clearInterval(this.intervalId);

      // 确定事件类型
      const event = e.type.includes("mouse") ? e : e.touches[0];

      this.isDragging = true;
      this.startX = event.pageX;
      this.scrollLeft = this.$refs.scrollContainer.scrollLeft;

      // 添加拖拽样式
      this.$refs.scrollContainer.classList.add("dragging");
      this.$refs.scrollContainer.style.cursor = "grabbing";
      this.$refs.scrollContainer.style.userSelect = "none";
    },

    // 拖拽过程
    drag(e) {
      if (!this.isDragging) return;

      // 防止默认行为
      e.preventDefault();

      // 确定事件类型
      const event = e.type.includes("mouse") ? e : e.touches[0];

      // 计算拖拽距离
      const x = event.pageX;
      const walk = (x - this.startX) * 1.5; // 拖拽系数，使拖拽更灵敏

      // 应用滚动
      this.$refs.scrollContainer.scrollLeft = this.scrollLeft - walk;
    },

    // 结束拖拽
    endDrag() {
      if (!this.isDragging) return;

      this.isDragging = false;

      // 移除拖拽样式
      this.$refs.scrollContainer.classList.remove("dragging");
      this.$refs.scrollContainer.style.cursor = "";
      this.$refs.scrollContainer.style.userSelect = "";

      // 计算应该显示的索引
      this.calculateCurrentIndex();

      // 平滑滚动到当前索引
      this.goToSlide(this.currentIndex);

      // // 重置自动轮播
      // this.resetAutoplay();
    },
  },
  mounted() {
    this.getDashboard();
    // this.resetAutoplay();

    // 添加滚动事件监听器
    this.$refs.scrollContainer.addEventListener("scroll", this.handleScroll);
  },
  beforeDestroy() {
    // 移除滚动事件监听器，防止内存泄漏
    this.$refs.scrollContainer.removeEventListener("scroll", this.handleScroll);
    clearInterval(this.intervalId);
  },
};
</script>

<style lang="scss" scoped>
// 定义变量，方便后续修改
$primary-color: #ffc107;
$text-color: #333;
$space-between-elements: 10px;

$carousel-indicator-size: 8px; // 指示圆点大小
$carousel-indicator-spacing: 6px; // 指示圆点间距

.rating-component {
  display: flex;
  justify-content: space-between;
  flex-direction: column; // 改为垂直布局，使圆点位于底部
  position: relative; // 为指示器定位提供参考
}

.scroll-container {
  overflow-x: auto; // 显示水平滚动条
  white-space: nowrap; // 防止内容换行
  scroll-snap-type: x mandatory; // 添加滚动吸附效果
  cursor: grab; // 鼠标悬停样式
  scroll-behavior: smooth; // 添加默认平滑滚动

  // 隐藏滚动条但保留功能
  &::-webkit-scrollbar {
    display: none;
  }
  &::-webkit-scrollbar-track {
    background-color: transparent;
  }
  &::-webkit-scrollbar-thumb {
    background-color: transparent;
    border-radius: 4px;
  }

  // 兼容 Firefox
  scrollbar-color: transparent transparent;
  scrollbar-width: none;

  // 拖拽状态
  &.dragging {
    cursor: grabbing;
    scroll-behavior: auto; // 拖拽时禁用平滑滚动
    scroll-snap-type: none; // 拖拽时禁用吸附效果
  }
}

.rating-info {
  display: inline-block; // 使 rating-info 盒子在一行显示
  margin-right: .0972rem;
  width: 2.2986rem;
  // height: 1.3681rem;
  overflow: hidden;
  background: #fff;
  position: relative;
  border: 1px solid #cdcccc;
  border-radius: 0.0556rem;
  scroll-snap-align: start; // 滚动吸附到每个卡片的开始位置

  .rating-star {
    padding: 16px 24px 0 16px;
    text-align: center;
    display: flex;
    width: 100%;
    height: 0.5764rem;
    border-radius: 0.0556rem;
    border: none !important;
    background: #d2ebff;
    box-sizing: border-box;

    .rating-star-image {
      width: 0.3542rem;
      height: 0.3472rem;
      margin-right: 16px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .rating-star-text {
      display: flex;
      flex-direction: column;
      text-align: start;

      .rating-star-title {
        font-size: .125rem;
        font-weight: 600;
        margin-bottom: 8px;
        color: #232323;
      }

      .rating-star-details {
        display: flex;
        align-items: center;
        text-align: center;

        .rating-value {
          font-size: .1111rem;
          font-weight: 600;
          color: #000;
        }
        .el-icon-star-on {
          padding: 0px 3px 0px 0px;
        }
        .rating-review-count {
          font-size: .0972rem;
          font-weight: 600;
          color: #454545;
          margin-left: 5px;
        }
      }
    }
  }

  .rating-empty-space {
    height: 0.0556rem;
    background: #fff;
  }

  .rating-response-rate {
    display: flex;
    flex-direction: column;
    width: 100%;
    // height: 0.7431rem;
    background: #fff;
    box-sizing: border-box;
    padding: 0px 24px 16px 24px;

    .response-rate-info {
      display: flex;
      font-size: .1111rem;
      margin-bottom: 8px;

      .response-rate-label {
        color: #454545;
        font-size: .1111rem;
        font-weight: 400;
      }

      .response-rate-value {
        font-weight: 600;
        margin-right: 8px;
        margin-left: 8px;
      }
    }

    .response-time-info {
      font-size: .0833rem;
      font-weight: 400;
      text-align: left;
      margin-bottom: 16px;
    }

    .el-progress-container {
      margin-bottom: 8px;
      width: 100%;
      ::v-deep .el-progress {
        border-radius: 8px; // 设置圆角
      }
      ::v-deep .el-progress-bar {
        padding-right: 0;
      }
      ::v-deep .el-progress-bar__outer {
        background-color: #fff; // 背景色
      }
      ::v-deep .el-progress-bar__inner {
        background-color: #2faa68; // 进度条颜色
      }
      ::v-deep .el-progress__text {
        display: none; // 隐藏百分比文本
      }
    }

    .number {
      margin-top: 8px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: .0833rem;
      font-weight: 400;
      width: 100%;

      .guests-num {
        margin-right: 32px;
        color: #6a6969;
        span {
          color: #232323;
        }
      }

      .reviews-num {
        color: #6a6969;
        span {
          color: #232323;
        }
      }
    }
  }
}

// 指示圆点样式
.carousel-indicators {
  position: absolute;
  bottom: -20px; // 调整位置，放在内容下方
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  gap: $carousel-indicator-spacing;
  z-index: 10;

  span {
    width: $carousel-indicator-size;
    height: $carousel-indicator-size;
    border-radius: .0556rem;
    background-color: rgba(205, 204, 204, 0.5); // 半透明灰色
    cursor: pointer;
    transition: background-color 0.3s, width 0.3s;

    &.active {
      background-color: #8f8f8f; // 激活状态颜色
      width: 25px;
    }
  }
}
</style>
